import React, { useState, useEffect, useContext } from 'react';
import { Form, Button, Input, Card, Space, Upload, message } from 'antd';
import { connect, Dispatch } from 'umi';
import { StateType } from '../../model';
import styles from './index.less';
import { MinusCircleOutlined, PlusOutlined, InboxOutlined } from '@ant-design/icons';
import { parseInt } from 'lodash';
import { WarningContext } from '../../index'
import request from 'umi-request';
const { Dragger } = Upload;
const formItemLayout = {
  labelCol: {
    span: 7,
  },
  wrapperCol: {
    span: 20,
  },
};
interface Settings {
  id: number,
  name?: string,
  num: number,
  status: number|boolean,
  updateDate?: Date
}
interface Step2Props {
  data?: StateType['step'];
  dispatch?: Dispatch;
  submitting?: boolean;
}
interface Attendant {
  uid: String;
}
const Step2: React.FC<Step2Props> = (props) => {
  const [form] = Form.useForm();
  const { data, dispatch, submitting } = props;
  const [fieldsNum, setFieldsNum] = useState<number>(0)
  // const [stepHeight, setStepHeight] = useState<number>(0)//Step2高度
  const [setting, setSetting] = useState<Settings>({})
  const [fileList, setFileList] = useState<Array<Attendant>>([])
  let { setWarning }:any = useContext(WarningContext);
  const fetchData = async (params:number) => {
    const msg = await request<{
      data: Settings,
    success: boolean
    }>(`/acs/api/setValue/${params}`);
    msg.data.status===1?true:false
    setSetting(msg.data)
      
  }
  useEffect(()=>{
    fetchData(1)
  },[])
  /**判断访客人数是否大于5人 */
  useEffect(() => {
    console.log(setting)
    if(setting.status===1){
          let fields = fieldsNum + 1
        //  let step = setting.num>5&&fieldsNum<5?17:setting.num*3.5
        //   setStepHeight(fields)
    if (fields > setting.num && fileList.length === 0) {
     
      setWarning( {
        remind:true,
        num: setting.num,
      })
    } else {
      setWarning( {
        remind:false,
        num: 0,
      })
    }
    }

  }, [fieldsNum, fileList])

  if (!data) {
    return null;
  }
  useEffect(() => {
    if(setting.status===1){
    if (fieldsNum < setting.num) {
      setFileList([])
    }
  }
  }, [fieldsNum])
  //返回上一步
  const { validateFields, getFieldsValue } = form;
  const onPrev = () => {
    if (dispatch) {
      const values = getFieldsValue();
      dispatch({
        type: 'initiateSubscribe/saveStepFormData',
        payload: {
          ...data,
          ...values,
          ...fileList,
        },
      });
      dispatch({
        type: 'initiateSubscribe/saveCurrentStep',
        payload: 'info',
      });
    }
  };
  //提交
  const onValidateForm = async () => {
    const values = await validateFields();
    let files = { fileList }
    if (dispatch) {
      let fields = fieldsNum + 1
      if (fields > setting.num && fileList.length === 0) {
        message.warning('请上传图片后再提交！！！');
        return
      } else {
        dispatch({
          type: 'initiateSubscribe/submitStepForm',
          payload: {
            ...data,
            ...values,
            ...files,
          },
        });
      }
    }
  };

  const pro: any = {
    name: 'file',
    multiple: true,
    action: '/api/acs/api/uploadFiles',
    listType: 'picture',
    defaultFileList: [...fileList],
    onChange(info: any) {
      const { status } = info.file;
      let file: Array<any> = [...info.fileList];

      if (status !== 'uploading') {
        file = file.map(item => {
          if (item.response) {
            // Component will show file.url as link
            item.name = item.response.data.filename
            item.url = `http://127.0.0.1:7601${item.response.data.url}`
          }
          return item;
        });
        setFileList(file)
      }
      if (status === 'done') {
        message.success(`图片上传成功 `);
      } else if (status === 'error') {
        message.error(`图片上传失败!`);
      }
    },
    onRemove(info: Attendant) {
      console.log(info)
      for (let i in fileList) {
        if (fileList[i].uid === info.uid) {
          fileList.splice(parseInt(i), 1)
        }
      }
    }
  };
  // const { payAccount, receiverAccount, receiverName, amount } = data;
  return (
    <Card bordered={false}>
      <div>
        <Form
          {...formItemLayout}
          form={form}
          layout="horizontal"
          className={styles.stepForm}
        >
          <Form.List name="attendant">
            {(fields, { add, remove }) => {
              setFieldsNum(fields.length)
              return (
                <div>
                  <div style={{ height: fieldsNum + 1 > 5 ? '' : `${setting.num>fieldsNum + 1?17:''}em` }}>
                    {fields.map(field => (
                      <Space key={field.key} className={styles.field} align="start">
                        <Form.Item
                          {...field}
                          label="姓名"
                          name={[field.name, 'name']}
                          fieldKey={[field.fieldKey, 'name']}
                          rules={[{ required: true, message: '请输入姓名' }]}
                        >
                          <Input placeholder="请输入同行人姓名" />
                        </Form.Item>
                        <Form.Item
                          {...field}
                          label="身份证号"
                          name={[field.name, 'idCard']}
                          fieldKey={[field.fieldKey, 'idCard']}
                          rules={[{ required: true, message: '请输入身份证号' }]}
                        >
                          <Input placeholder="请输入同行人身份证号" />
                        </Form.Item>
                        <Form.Item
                          {...field}
                          label="手机号"
                          name={[field.name, 'phone']}
                          fieldKey={[field.fieldKey, 'phone']}
                          rules={[{ required: true, message: '请输入手机号' }]}
                        >
                          <Input placeholder="请输入同行人手机号" />
                        </Form.Item>
                        <MinusCircleOutlined
                          onClick={() => {
                            remove(field.name);
                          }}
                        />
                      </Space>
                    ))}
                  </div>
                  {setting.status===1&&fieldsNum + 1 > setting.num ? (<Form.Item
                    className={styles.addField}
                  >
                    <Dragger {...pro} className={styles.picture}>
                      <p className="ant-upload-drag-icon">
                        <InboxOutlined />
                      </p>
                      <p className="ant-upload-text">点击上传图片</p>
                    </Dragger>

                  </Form.Item>) : ('')
                  }
                  <Form.Item className={styles.addField}>
                    <Button
                      type="dashed"
                      onClick={() => {
                        add();
                      }}
                      block>
                      <PlusOutlined /> 添加同行人员
                </Button>
                  </Form.Item>
                </div>
              );
            }}
          </Form.List >
          <Form.Item
            className={styles.submit}
            style={{ marginBottom: 8 }}
            wrapperCol={{
              xs: { span: 24, offset: 0 },
              sm: {
                span: formItemLayout.wrapperCol.span,
                offset: formItemLayout.labelCol.span,
              },
            }}
          >
            <div>
              <Button onClick={onPrev}>
                上一步
        </Button>
              <Button type="primary" onClick={onValidateForm} style={{ marginLeft: '20px' }} loading={submitting}>
                提交
        </Button>
            </div>
          </Form.Item>
        </Form>
      </div>
    </Card>
  );
};
export default connect(
  ({
    initiateSubscribe,
    loading,
  }: {
    initiateSubscribe: StateType;
    loading: {
      effects: { [key: string]: boolean };
    };
  }) => ({
    submitting: loading.effects['initiateSubscribe/submitStepForm'],
    data: initiateSubscribe.step,
  })
)(Step2);
